import React, { useEffect, useState, useRef } from 'react'
import { Tabs, Row, Col, Input, Slider, Select } from 'antd'
import FlowGraph from '@/pages/Graph'
import { Cell } from '@antv/x6'
// @ts-ignore
import reqwest from 'reqwest'

const { TabPane } = Tabs
const { TextArea } = Input
const { Option } = Select

interface IProps {
  id: string
}
interface NodeAttrs {
  stroke: string
  strokeWidth: number
  fill: string
  fontSize: number
  color: string
  val: string
  des: string
  display: string
  logicType: string
  relationId: string
  _type: string
  condition: string
  result: string
}

export default function (props: IProps) {
  const { id } = props
  const [attrs, setAttrs] = useState<NodeAttrs>({
    stroke: '#5F95FF',
    strokeWidth: 1,
    fill: 'rgba(95,149,255,0.05)',
    fontSize: 12,
    color: 'rgba(0,0,0,0.85)',
    val: '',
    des: '',
    display: '',
    logicType: '',
    relationId: '',
    _type: '',
    condition: '',
    result: ''
  })
  const [pageType, setPageType] = useState<any>(null)
  const [configDisabled, setConfigDisabled] = useState<boolean>(false)

  const [data, setData] = useState({
    relationList: []
  })

  const cellRef = useRef<Cell>()

  useEffect(() => {
    if (id) {
      const { graph, pageType } = FlowGraph
      const cell = graph.getCellById(id)
      setPageType(pageType)
      if (!cell || !cell.isNode()) {
        return
      }
      if (pageType == "1" && cell.data.type == "0") { // 推理页面描述节点禁止编辑配置项
        setConfigDisabled(true)
      } else {
        setConfigDisabled(false)
      }
      //初始化节点数据id
      cell.data.id = id
      cellRef.current = cell
      let circle = 'none';
      //逻辑节点显示选项
      if (cell.data.type === "4") {
        circle = 'flex'
      }

      if (cell.data.type === "3") {
        // @ts-ignore
        if (top.DIALOG) {
          // @ts-ignore
          let showId = top.DIALOG.showIds.top();
          // @ts-ignore
          let _id = top.DIALOG.get(showId).state.data
          if (FlowGraph.pageType == "1") {
            _id = _id.malfunction_id
          }
          if (typeof (_id) != "string") {
            _id = _id.id;
          }
          reqwest({
            method: 'post',
            url: '/OMDS/api/rest/malfunction/getRelationSelection',
            data: { data: _id },
            success: function (res: any) {
              if (res.code == 200) {
                setData({ relationList: res.data })
              }
            }
          })
        }

      }

      setAttrs({
        stroke: cell.attr('body/stroke'),
        strokeWidth: cell.attr('body/strokeWidth'),
        fill: cell.attr('body/fill'),
        fontSize: cell.attr('text/fontSize'),
        color: cell.attr('text/fill'),
        val: cell.attr('text/textWrap/text'),
        des: cell.data.des,
        display: circle,
        logicType: cell.data.logicType,
        relationId: cell.data.relationId,
        _type: cell.data.type,
        condition: cell.attr('condition/textWrap/text'),
        result: cell.data.result
      })
    }
  }, [id])


  const setAttr = (key: string, val: any) => {
    setAttrs((prev) => ({
      ...prev,
      [key]: val,
    }))
  }

  const onStrokeChange = (e: React.FocusEvent<HTMLInputElement>) => {
    const val = e.target.value
    setAttr('stroke', val)
    cellRef.current!.attr('body/stroke', val)
  }

  const onStrokeWidthChange = (val: number) => {
    setAttr('strokeWidth', val)
    cellRef.current!.attr('body/strokeWidth', val)
  }

  const onFillChange = (e: React.FocusEvent<HTMLInputElement>) => {
    const val = e.target.value
    setAttr('fill', val)
    cellRef.current!.attr('body/fill', val)
  }

  const onFontSizeChange = (val: number) => {
    setAttr('fontSize', val)
    cellRef.current!.attr('text/fontSize', val)
  }

  const onColorChange = (e: React.FocusEvent<HTMLInputElement>) => {
    const val = e.target.value
    setAttr('color', val)
    cellRef.current!.attr('text/fill', val)
  }

  const onValueChange = (e: React.FocusEvent<HTMLInputElement>) => {
    const value = e.target.value
    setAttr('val', value)
    cellRef.current!.attr("text/textWrap/text", value)
    cellRef.current!.data.text = value;
  }

  const onConditionChange = (e: React.FocusEvent<HTMLInputElement>) => {
    const value = e.target.value
    setAttr('condition', value)
    cellRef.current!.attr("condition/textWrap/text", value)
    cellRef.current!.data.condition = value;
  }

  const onDesChange = (e: React.FocusEvent<HTMLInputElement>) => {
    const value = e.target.value
    setAttr('des', value)
    cellRef.current!.data.des = value;
  }

  const onLogicTypeChange = (val: string) => {
    setAttr('logicType', val)
    cellRef.current!.data.logicType = val
  }

  const onSelectRelation = (val: string, option: any) => {
    setAttr('relationId', option.value)
    cellRef.current!.attr("text/textWrap/text", option.children)
    cellRef.current!.data.id = option.value
    cellRef.current!.data.relationId = option.value
    cellRef.current!.data.text = option.children
  }

  const onSelectTrueOrFalse = (val: string, option: any) => {
    setAttr('result', option.value)
    if (!cellRef.current!.data.score) {
      cellRef.current!.data.score = 0;
    }
    // if (val == "1") {
    //    cellRef.current!.data.score++;
    // }
    // if (val == "0") {
    //   if (cellRef.current!.data.score > 0) {
    //     cellRef.current!.data.score--;
    //   }
    // }
    FlowGraph.updateInferenceResultData(val, cellRef.current); // 更新推理结果分数

    cellRef.current!.data.result = option.value
    cellRef.current!.data.resultText = option.children
  }

  const getTrueOrFalseSelect = () => {
    // if (!FlowGraph.inferenceRecord) {
    //   return "";
    // }
    if (cellRef.current) {
      let cell = cellRef.current
      return (
        pageType && pageType == "1" && attrs._type != "0" ? <Row align="middle">
          <Col span={8}>是否正确</Col>
          <Col span={16}>
            <Select style={{ width: '100%' }} onChange={onSelectTrueOrFalse} value={attrs.result}>
              <Option value="1">正确</Option>
              <Option value="0">错误</Option>
            </Select>
          </Col>
        </Row> : ''
      )
    }
  }

  if (attrs._type == "4" || attrs._type == "5" || attrs._type == "6" || attrs._type == "7") { // 异或节点
    return (
      <Tabs defaultActiveKey="0">
        <TabPane tab="内容" key="0">
          <Row align="middle">
            <Col span={8}>节点描述</Col>
            <Col span={16}>
              <Input
                value={attrs.val}
                onChange={onValueChange}
                readOnly
              />
            </Col>
          </Row>
          {
            attrs._type == "7" ? <Row align="middle">
              <Col span={8}>条件</Col>
              <Col span={16}>
                <TextArea
                  value={attrs.condition}
                  autoSize
                  // @ts-ignore
                  onChange={onConditionChange}
                />
              </Col>
            </Row> : ''
          }
          <Row align="middle">
            <Col span={8}>节点说明</Col>
            <Col span={16}>
              <TextArea
                value={attrs.des}
                autoSize
                // rows={4}
                // @ts-ignore
                onChange={onDesChange}
              />
            </Col>
          </Row>
        </TabPane>
      </Tabs>
    )
  } else if (attrs._type == "3") {
    return (
      <Tabs defaultActiveKey="0">
        <TabPane tab="内容" key="0">
          <Row align="middle">
            <Col span={8}>链接节点</Col>
            <Col span={16}>
              <Select style={{ width: '100%' }} onChange={onSelectRelation} value={attrs.relationId} showSearch filterOption={(input: any, option: any) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }>
                {
                  data.relationList.map(item => (
                    // @ts-ignore
                    <Select.Option value={item.code}>{item.text}</Select.Option>
                  ))
                }
              </Select>
            </Col>
          </Row>
          {
            getTrueOrFalseSelect()
          }
          <Row align="middle">
            <Col span={8}>节点说明</Col>
            <Col span={16}>
              <TextArea
                value={attrs.des}
                autoSize
                // rows={4}
                // @ts-ignore
                onChange={onDesChange}
              />
            </Col>
          </Row>
        </TabPane>
      </Tabs>
    )
  } else {
    return (
      <Tabs defaultActiveKey="0">
        <TabPane tab="内容" key="0">
          <Row align="middle">
            <Col span={8}>节点描述</Col>
            <Col span={16}>
              <TextArea
                value={attrs.val}
                autoSize
                // @ts-ignore
                onChange={onValueChange}
                disabled={configDisabled}
              />
            </Col>
          </Row>
          <Row align="middle" style={{ display: attrs.display }}>
            <Col span={8}>逻辑类型</Col>
            <Col span={16}>
              <Select value={attrs.logicType} style={{ width: '100%' }} onChange={onLogicTypeChange}>
                <Select.Option value="0">与门</Select.Option>
                <Select.Option value="1">或门</Select.Option>
                <Select.Option value="2">非门</Select.Option>
                <Select.Option value="3">与非门</Select.Option>
                <Select.Option value="4">或非门</Select.Option>
              </Select>
            </Col>
          </Row>
          {
            getTrueOrFalseSelect()
          }
          <Row align="middle">
            <Col span={8}>节点说明</Col>
            <Col span={16}>
              <TextArea
                value={attrs.des}
                autoSize
                // rows={4}
                // @ts-ignore
                onChange={onDesChange}
              />
            </Col>
          </Row>
        </TabPane>
        <TabPane tab="文本" key="2">
        <Row align="middle">
          <Col span={8}>字体大小</Col>
          <Col span={12}>
            <Slider
              min={8}
              max={20}
              step={1}
              value={attrs.fontSize}
              onChange={onFontSizeChange}
            />
          </Col>
          <Col span={2}>
            <div className="result">{attrs.fontSize}</div>
          </Col>
        </Row>
        <Row align="middle">
          <Col span={8}>字体颜色</Col>
          <Col span={14}>
            <Input
              type="color"
              value={attrs.color}
              style={{ width: '100%' }}
              onChange={onColorChange}
            />
          </Col>
        </Row>
      </TabPane>
      </Tabs>
    )
  }

}
